<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="name" placeholder="请输入内容" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"></el-input>
      <!--      <el-select v-model="listQuery.importance" placeholder="订单状态" clearable style="width: 120px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-circle-plus" @click="handlecreate">
        新增
      </el-button>
    </div>
    <el-table

      v-loading="listLoading"
      :data="list"
      tablder
      fit
      highlight-current-row
      style="width: 100%;"

    >
      <el-table-column prop="index" label="序号" align="center" width="80" fixed>
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品名称" prop="goodName" align="center">
      </el-table-column>

      <el-table-column label="商品库存" prop="goodCount" align="center">
      </el-table-column>

      <el-table-column label="商品价格" prop="goodPrice" align="center">
      </el-table-column>

      <el-table-column label="分类" prop="categoryId" align="center">
      </el-table-column>

      <el-table-column label="图片" prop="goodImage" align="center">
<!--        图片-->
        <template slot-scope="{ row }">
          <el-image style="width: 90px; height: 90px; border:none;cursor: pointer;"
                    :src="getImage(row.goodImage)"
                     >
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="描述" prop="goodDescription" width="325px"  align="center">
      </el-table-column>

      <el-table-column label="上架时间" prop="createTime" align="center">
      </el-table-column>

      <el-table-column label="修改时间" prop="updateTime" align="center">
      </el-table-column>
      <!--      操作-->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="row">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row.row.goodId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--    分页-->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </div>

    <!--    编辑框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="commonGoods" :rules="rules" :model="commonGoods" label-position="left" label-width="70px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="商品名称" prop="type">
          <el-input v-model="commonGoods.goodName"/>
        </el-form-item>
        <el-form-item label="商品库存" prop="timestamp">
          <el-input v-model="commonGoods.goodCount"/>
        </el-form-item>
        <el-form-item label="商品价格" prop="title">
          <el-input v-model="commonGoods.goodPrice"/>
        </el-form-item>
        <el-form-item label="商品分类">

            <div class="block">
              <el-cascader
                v-model="value"
                :options="options"
                @change="handleChange">
              </el-cascader>
            </div>
          <el-select v-model="selectfromtype" placeholder="选择详细类型">
            <el-option
              v-for="type in diclist"
              :value="type.dcId"
              :key="type.dcId"
              :label="type.dcName"
              ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片">
          <div class="addBrand-container" id="food-add-app">
            <div class="container">
              <el-upload class="avatar-uploader"
                         action="http://localhost:9527/dev-api/common/upload"
                         :on-success="handleAvatarSuccess"
                         :show-file-list="false"
                         :before-upload="beforeUpload"
              >
                <!--                        -->
                <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="描述">
          <el-input v-model="commonGoods.goodDescription" :autosize="{ minRows: 2, maxRows: 4}" type="textarea"
                    placeholder="Please input"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>

        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>

    </el-dialog>

    <!--    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">-->
    <!--      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">-->
    <!--        <el-table-column prop="key" label="Channel" />-->
    <!--        <el-table-column prop="pv" label="Pv" />-->
    <!--      </el-table>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>-->
    <!--      </span>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import {fetchList, fetchPv, createArticle, updateArticle} from '@/api/article'
import waves from '@/directive/waves' // waves directive
import {parseTime} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination


import {addGood, deletegoods, getgood, Updategoods} from "@/api/goods";
import {getByIddic, gettypedic} from "@/api/commondic";

const calendarTypeOptions = [
  {key: 'CN', display_name: 'China'},
  {key: 'US', display_name: 'USA'},
  {key: 'JP', display_name: 'Japan'},
  {key: 'EU', display_name: 'Eurozone'}
]

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})


export default {
  name: 'ComplexTable',
  components: {Pagination},
  directives: {waves},

  data() {
    return {
      selectfromtype:'',
      options: [{
        value: '1',
        label: '案例风格',
        children: [{
          value: '2',
          label: '工装风',

        }, {
          value: '3',
          label: '波西米亚风',
        }]
      }, {
        value: '4',
        label: '商品分类',
        children: [{
          value: '5',
          label: '建材类',
        }, {
          value: '6',
          label: '布衣类',
        }, {
          value: '7',
          label: '五金类',
        }, {
          value: '8',
          label: '电器类',
        }, {
          value: '9',
          label: '装饰类',
        }]

      }],
      value:'',
      //分类value，label
      diclist:[],
      //表格列表
      list: [],
      //搜索框
      name: "",
      imageUrl: '',
      //分页总数
      total: 0,
      //当前页
      currentPage: 1,
      //每页多少条
      pagesizes: 5,

      commonGoods: {
        //编辑
        // goodName:"",
        // goodCount:'',
        // goodPrice:'',
        // goodDescription:"",
        // createTime:new Date(),
        // updateTime:new Date()

      },


      //搜索下拉列表
      // importanceOptions: [1, 2, 3],
      tableKey: 0,
      diclistname:[],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      sortOptions: [{label: 'ID Ascending', key: '+id'}, {label: 'ID Descending', key: '-id'}],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        // type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getgood(this.name, this.currentPage, this.pagesizes).then(res => {

        console.log(res)
        this.list = res.data.records
        this.total = res.data.total
        // console.log(this.list[0].categoryId)

        for (let k in this.list){
          console.log(this.list[k].categoryId)
          getByIddic(this.list[k].categoryId).then(res=>{
            // console.log(res.data.dcName)
            console.log(this.list[k].categoryId=res.data.dcName)
          })
          console.log(this.list)
        }
        this.listLoading = false
      })
    },
    //删除
    handleDelete(id) {

      console.log(id)

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletegoods(id).then(res => {
          console.log(res)
          this.$notify({
            title: res.data,
            message: res.data,
            type: 'success',
            duration: res.code
          })
        })
        this.getList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    //搜索框
    handleFilter() {
      this.getList()
    },
    //编辑
    handleUpdate(row) {
      //清空风格
      this.selectfromtype=null
      this.value={}

      console.log(row.row)
      this.commonGoods = row.row
      this.commonGoods.goodId=row.row.goodId
      // this.commonGoods.goodImage=row.row.goodImage
      this.imageUrl = `http://localhost:9527/dev-api/common/download?name=${row.row.goodImage}`
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getList();

    },
    //新增
    handlecreate() {
      //清空风格
      this.selectfromtype=null
      this.value={}

      this.imageUrl=`http://localhost:9527/dev-api/common/download?name=555555.jpg`
      this.commonGoods = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

    },
    //更新
    updateData() {
      this.commonGoods.updateTime = new Date()
      console.log(this.commonGoods.categoryId=this.selectfromtype)
      Updategoods(this.commonGoods).then(res=>{
        console.log(res)
      })
      this.getList();
      this.dialogFormVisible=false
    },
    //新增
    createData() {
      console.log("add")
      console.log(this.selectfromtype)
      console.log(this.commonGoods.categoryId=this.selectfromtype)
      addGood(this.commonGoods).then(res => {
        console.log(res)
        this.$notify({
          title: res.data,
          message: res.data,
          type: 'success',
          duration: res.code
        })
      })
      this.getList()
      this.dialogFormVisible = false
      this.getList()
    },
    // 分页
    handleSizeChange(val) {
      this.pagesizes = val
      console.log(this.pagesizes)
      this.getList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(this.currentPage);
      this.getList()
    },


    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },

    //图片
    handleAvatarSuccess(response, file, fileList) {
      this.imageUrl = `http://localhost:9527/dev-api/common/download?name=${response.data}`
      this.commonGoods.goodImage=response.data
    },
    getImage (image) {
      // console.log("imageimageimag")
      // console.log(image)
      return `http://localhost:9527/dev-api/common/download?name=${image}`
    },
    beforeUpload(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 15
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 15MB!')
          return false
        }
        return file
      }
    },
    handleChange(value) {
      gettypedic(this.value[1]).then(res=>{
        console.log(this.diclist=res.data)
      })
    }

  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

